
/*
 * =========================================================================
 *
 *       FileName:  circular_buffer.c
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  2023-10-16 21:37:01
 *  Last Modified:  2023-10-16 21:39:42
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  zt ()
 *   Organization:
 *
 * =========================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

#define SIZE (10)
typedef struct
{
  int buffer[SIZE];
  int head;
  int tail;
  int count;
} CircularBuffer;

void push ( CircularBuffer* cb, int data )
{
  if ( cb->count < SIZE )
  {
    cb->buffer[cb->head] = data;
    cb->head = ( cb->head + 1 ) % SIZE;
    cb->count++;
  }
}

int pop ( CircularBuffer* cb )
{
  if ( cb->count > 0 )
  {
    int data = cb->buffer[cb->tail];
    cb->tail = ( cb->tail + 1 ) % SIZE;
    cb->count--;
    return data;
  }

  return -1; // Buffer is empty
}


int main ( int argc, char* argv[] )
{
  ( void ) argc;
  ( void ) argv;

  CircularBuffer c;
  c.head = 0;
  c.tail = 0;
  c.count = 0;

  push ( &c, 1 );
  push ( &c, 3 );
  push ( &c, 4 );
  push ( &c, 8 );

  printf ( "pop = %d\n", pop ( &c ) );
  printf ( "pop = %d\n", pop ( &c ) );
  printf ( "pop = %d\n", pop ( &c ) );
  printf ( "pop = %d\n", pop ( &c ) );
  printf ( "pop = %d\n", pop ( &c ) );


  return 0;
}

